// 从本地提出数据
let products = localStorage.getItem('CARTLIST')
products = JSON.parse(products)

// 全选状态
let stateAll = false

// 将商品数据渲染到界面
function showProductList() {
  let str = `<tr class='head'>
        <td><input type="checkbox" class="checkbox-all" ${stateAll ? 'checked' : ''}></td>
        <th>商品ID</th>
        <th>商品图片</th>
        <th>商品信息</th>
        <th>单价</th>
        <th>数量</th>
        <th>总价</th>
        <th>操作</th>
      </tr> 
    `
  products.forEach((item, index) => {
    let mesgStr = `
        <tr>
            <td><input type="checkbox" class="checkbox-item" ${item.state ? 'checked' : ''}></td>
            <td>${item.id}</td>
            <td><img src="${item.img}" width=75 height=96 alt="shop03"></td>
            <td>${item.name}</td>
            <td>￥${item.price}</td>
            <td width=100><input type="button" name="minus" value="-" ${item.num == 0 ? 'disabled' : ''}><input type="text" name="amount"  value="${item.num}"><input type="button" name="plus" value="+"></td>
            <td class="singleprice" width="100px">￥${item.singlePrice}</td>
            <td><a class="delete-btn" href="#">删除</a></td>
        </tr>
      `
    str += mesgStr
  })
  $('.cartList').html(str)
}

// 操作商品
function operateProduct() {
  // 输入添加/减少商品数量
  $('.cartList').on('change', 'input[name="amount"]', function () {
    let id = $(this).parent().prev().prev().prev().prev().html()
    let product = products.find(item => item.id == id)
    let num = $(this).val()
    product.num = num
    product.singlePrice = (product.num * product.price).toFixed(2)
    localStorage.setItem('CARTLIST', JSON.stringify(products))
    getTotalPrice()
    showProductList()
  })

  // 删除商品
  $('.cartList').on('click', '.delete-btn', function () {
    let id = $(this).parent().prev().prev().prev().prev().html()
    let index = products.findIndex(item => item.id == id)
    products.splice(index, 1)
    localStorage.setItem('CARTLIST', JSON.stringify(products))
    getTotalPrice()
    showProductList()
  })

  // 商品数量增加
  $('.cartList').on('click', 'input[name="plus"]', function () {
    let id = $(this).parent().prev().prev().prev().prev().html()
    let product = products.find(item => item.id == id)
    product.num++
    product.singlePrice = (product.num * product.price).toFixed(2)
    localStorage.setItem('CARTLIST', JSON.stringify(products))
    getTotalPrice()
    showProductList()
  })

  // 商品数量减少
  $('.cartList').on('click', 'input[name="minus"]', function () {
    let id = $(this).parent().prev().prev().prev().prev().html()
    let product = products.find(item => item.id == id)
    product.num--
    product.singlePrice = (product.num * product.price).toFixed(2)
    localStorage.setItem('CARTLIST', JSON.stringify(products))
    getTotalPrice()
    showProductList()
  })

  // 全选
  $('.cartList').on('click', '.checkbox-all', function () {
    stateAll = !stateAll
    if (stateAll) {
      products.forEach((item) => (item.state = true))
    } else {
      products.forEach((item) => (item.state = false))
    }
    localStorage.setItem('CARTLIST', JSON.stringify(products))
    localStorage.setItem('STATEALL', JSON.stringify(stateAll))
    showProductList()
  })

  // 单选
  $('.cartList').on('click', '.checkbox-item', function () {
    let id = $(this).parent().next().html()
    let product = products.find(item => item.id == id)
    product.state = !product.state
    stateAll = products.every(item => item.state == true)
    localStorage.setItem('CARTLIST', JSON.stringify(products))
    localStorage.setItem('STATEALL', JSON.stringify(stateAll))
    showProductList()
  })
}

// 计算总价
function getTotalPrice() {
  let total = products.reduce((s, item) => (s += Number(item.singlePrice)), 0)
  $('.totalPrice').html("￥" + total.toFixed(2))
}

// 结算
function settlement() {
  $('.settlement>.js').on('click', function () {
    let user = JSON.parse(localStorage.getItem('LOGINUSER')) || []
    console.log(user);
    if (user.length == 0) {
      alert('请先登录')
    } else {
      alert('结算成功')
      localStorage.clear()
      location.href = '../pages/index.html'
    }
  })
}

// 点击登录/注册
function toLoginOrRegister() {
  $('.ueser').on('click', '.login', function () {
    location.href = '../pages/login.html'
  })

  $('.ueser').on('click', '.register', function () {
    location.href = '../pages/register.html'
  })
}

// 获取登录后的用户名
function getUsername() {
  let url = location.href
  let index = url.indexOf('?')
  let subUrl = url.substring(index + 1)
  let name = subUrl.split('=')[1]
  return name
}

// 将登录后的用户信息显示到页面
function showUsername() {
  let name = getUsername()
  if (name) {
    $('.ueser').html('您好,' + name)
  }
}

showProductList()
operateProduct()
getTotalPrice()
settlement()
toLoginOrRegister()
showUsername()